package at.irian.jsfatwork.service.impl;

import at.irian.jsfatwork.dao.DishDao;
import at.irian.jsfatwork.domain.Dish;
import at.irian.jsfatwork.domain.Provider;
import at.irian.jsfatwork.service.DishService;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.util.List;

@Named("dishService")
@Singleton
public class DishServiceImpl implements DishService {

    @Inject
    private DishDao dishDao;

    public Dish createNew() {
        return dishDao.createNew();
    }

    public Dish createNew(Provider provider) {
        Dish dish = createNew();
        dish.setProvider(provider);
        return dish;
    }

    @Transactional
    public void save(Dish dish) {
        if (dish.isTransient()) {
            dish.getProvider().getDishes().add(dish);
            dishDao.persist(dish);
        }
    }

    @Transactional
    public void delete(Dish dish) {
        Provider provider = dish.getProvider();
        if (provider != null) {
            provider.getDishes().remove(dish);
        }
        dishDao.delete(dish);
    }

    @Transactional(readOnly = true)
    public List<Dish> findAll() {
        return dishDao.findAll();
    }

    @Transactional(readOnly = true)
    public Dish findById(long id) {
        return dishDao.findById(id);
    }

}
